package com.springboot.frame;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.UUID;

/**
 * @author liheng
 */
@Slf4j
@Component
public class MailSendTemplate {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送人须为授权用户，既配置文件中指定的授权码账户邮箱
     * 否则
     * com.sun.mail.smtp.SMTPSenderFailedException: 553 Mail from must equal authorized user
     */
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送文本邮件
     *
     * @param to
     * @param personal
     * @param subject
     * @param content
     */
    public void sendSimpleMail(String to, String personal, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(new InternetAddress(from, personal, "UTF-8").toString());
            message.setTo(to);
            // 抄送自己一份，防止当成垃圾邮件
            message.setCc(from);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            log.info("简单邮件已经发送");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常！", e);
        }

    }

    /**
     * 发送html邮件
     *
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMail(String to, String personal, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(new InternetAddress(from, personal, "UTF-8"));
            // 抄送自己一份，防止当成垃圾邮件
            helper.setCc(from);
            helper.setTo(to);
            helper.setSubject(subject);
            //true指的是html邮件，false指的是普通文本
            helper.setText(content, true);
            mailSender.send(message);
            log.info("html邮件发送成功");
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送html邮件时发生异常！", e);
        }
    }


    /**
     * 根据thymeleaf模板发送邮件
     *
     * @param to
     * @param subject
     * @param datas
     * @return
     */
    public void sendHtmlByThymeleafTemplate(String to,String personal, String subject, Map<String, Object> datas) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(new InternetAddress(from, personal, "UTF-8"));
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            Context context = new Context();
            context.setVariable("datas", datas);
            messageHelper.setText(templateEngine.process("emailTemplate", context), true);
            mailSender.send(message);
            log.info("发送Thymeleaf html模板邮件成功");
        } catch (MessagingException  | UnsupportedEncodingException e) {
            log.error("发送Thymeleaf html模板邮件时发生异常！", e);
        }
    }


    /**
     * 发送带附件的邮件
     *
     * @param to
     * @param subject
     * @param content
     * @param filePath
     */
    public void sendAttachmentsMail(String to,String personal,  String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(new InternetAddress(from, personal, "UTF-8"));
            // 抄送自己一份，防止当成垃圾邮件
            helper.setCc(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            if (!file.exists()) {
                log.error("附件不存在，发送失败！");
                return;
            }
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
            mailSender.send(message);
            log.info("带附件的邮件已经发送。");
        } catch (MessagingException  | UnsupportedEncodingException e) {
            log.error("发送带附件的邮件时发生异常！", e);
        }
    }


    /**
     * 发送正文中有静态资源（图片）的邮件
     *
     * @param to
     * @param subject
     * @param content
     * @param rscPath
     */
    public void sendInlineResourceMail(String to,String personal, String subject, String content, String rscPath) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(new InternetAddress(from, personal, "UTF-8"));
            // 抄送自己一份，防止当成垃圾邮件
            helper.setCc(from);
            helper.setTo(to);
            helper.setSubject(subject);
            String rscId = UUID.randomUUID().toString();
            String html = "<div><h1><a name=\"hello\"></a><span>Hello</span></h1><blockquote><p><span>this is a html email.</span></p></blockquote><p>&nbsp;</p><p><span>"
                    + content + "</span></p><img src='cid:" + rscId + "' /></div>";
            helper.setText(html, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            if (!res.exists()) {
                log.error("图片不存在，发送失败！");
                return;
            }
            helper.addInline(rscId, res);
            mailSender.send(message);
            log.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException | UnsupportedEncodingException e) {
            log.error("发送嵌入静态资源的邮件时发生异常！", e);
        }
    }
}
